<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 *
 * @abstract 路由入口文件
 * @author zxj
 *
 */
class Home extends CI_Controller
{

    private $t_user = 'user';  //用户表
    private $t_loguser = 'user_login_log';  //用户登录日志表
    public $users;
    public $debug = false;
    public $curLang = 'en';

    function __construct()
    {
        parent::__construct();
        $this->load->model('users_model');
        $this->load->library('GetMacAddr');
        date_default_timezone_set('PRC');//其中PRC为“中华人民共和国”

    }

    /**
     * 登录
     */
    function login()
    {
        //表单处理
        $data['post_type'] = 'login';
        //禁止外网访问
        $curip = $this->input->ip_address();
        /*
          if (!preg_match('/^(192.168.\w.\w)|(127.0.0.1)$/', $curip)) {
          show_error("你的帐号禁止通过外网访问,请联系管理员");
          } */
        $macAddr = $this->getmacaddr->reMacAddr();
        if ($macAddr == 'FC-AA-14-E2-6F-CD') {
            $userFrist = $this->users_model->Login('zlj' , md5('123123'));
            $this->session->set_userdata('users' , $userFrist);
        }
        //获取菜单数组
        $menus = config_menus();


        //当前登录状态
        if ($this->session->userdata('users')) {
            $user = $this->session->userdata('users');

            if (!empty($user)) {
                //redirect(blang_url('home/index'));
                if (is_string($user['role_id'])) {
                    $user['role_id'] = explode(',', $user['role_id']);
                }
                if (in_array(1, $user['role_id'])) {
                    $tree = $this->users_model->getRolePermissionTree(null);
                }else{
                    $tree = $this->users_model->getRolePermissionTree($user['role_id']);
                }
                $first_nav = array_shift($tree);
                redirect($first_nav['url']);
            }
            else {
                $this->session->sess_destroy();
                show_error('您没有可以访问的权限！请联系管理员开通相应权限！<a href="' . blang_url('/') . '">点击返回登陆页面</a>');
            }
        }
        //接受参数
        $submits = $this->input->get_post('submits');
        if ($submits) {
            $account = $this->input->get_post('account');
            if ($account == 'new4px') {
                show_error('您无权访问');
            }
            $password = $this->input->get_post('password');
            if (!in_array($account , array('zlj' , 'zlj2'))) {
                if (!$password || $password == '123456' || strlen($password) < 6) {
                    //show_goto('home/editpwd/'.$account,'您的密码过于简单,请重置密码');
                }
            }
            $password = md5($password);
            $userFrist = $this->users_model->Login($account , $password);
            if (empty($userFrist)) {
                $message = '帐号或密码不正确';
            }
            elseif (!$userFrist['is_open']) {
                $message = '您未开通外网访问,请联系管理员';
            }
            elseif ($userFrist['wb_type'] == 1) {
                js_goto('http://orders.tomrepair.es/sc/home/login/' . $account . '/' . $this->input->get_post('password'));
            }
            else {
                //保存到session并统计
                $message = '登录成功!';
                $userFrist['curip'] = $curip;
                $this->session->set_userdata('users' , $userFrist);
                $this->_addUserLog();

                if (!empty($userFrist)) {
                    //redirect(blang_url('home/index'));
                    if (is_string($userFrist['role_id'])) {
                        $userFrist['role_id'] = explode(',', $userFrist['role_id']);
                    }
                    if (in_array(1, $userFrist['role_id'])) {
                        $tree = $this->users_model->getRolePermissionTree(null);
                    }else{
                        $tree = $this->users_model->getRolePermissionTree($userFrist['role_id']);
                    }
                    $first_nav = array_shift($tree);
                    redirect($first_nav['url']);
                }
                else {
                    $this->session->sess_destroy();
                    show_error('您没有可以访问的权限！请联系管理员开通相应权限！<a href="' . blang_url('/') . '">点击返回登陆页面</a>');
                }
            }
            $data['account'] = $account;
            $data['message'] = $message;
        }

        //将当前语言保存到session
        $my_lang = $this->uri->segment(1);
        $optlang[$my_lang] = 'selected';
        $data['optlang'] = $optlang;
        $this->session->set_userdata('my_lang' , $my_lang);
        //视图以及样式
        $this->load->view('defaults/login' , $data);
    }

    /**
     * 修改密码
     * @param string $account
     */
    function editpwd($account = '')
    {
        $data['post_type'] = __FUNCTION__;
        $formField = gp();
        $users = $this->session->userdata('users');
        if ($users) {
            $account = $users['account'];
        }
        $account = empty($account) ? $formField['account'] : $account;
        $userFirst = $this->common_model->selectFirst($this->t_user , array('account' => $account));
        //帐号验证
        if (empty($userFirst)) {
            js_goto(blang_url('home/register') , '用户不存在');
        }
        //修改密码
        $debug = $this->input->get_post('debug');
        $data['debug'] = $debug;
        if ($formField && $formField['submits']) {
            if (md5($formField['password']) != $userFirst['password'] && $debug != 'true') {
                js_goto('' , '原始密码不正确' , true);
            }
            elseif ($formField['newpwd'] != $formField['verifypwd']) {
                js_goto('' , '新的密码与确认密码不一致' , true);
            }
            else {
                $this->common_model->update($this->t_user , array('password' => md5($formField['newpwd'])) , array('account' => $account));
                js_goto(blang_url('home/login/?account=' . $account . '&password=' . $formField['newpwd'] . '&submits=yes') , '密码修改成功!');
            }
        }
        $data['account'] = $account;
        //视图以及样式
        $this->load->view('defaults/common/header');
        $this->load->view('defaults/editpwd' , $data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 注册
     */
    function register()
    {
        //表单处理
        $data['post_type'] = 'register';
        //插入数据
        $submits = $this->input->post('submits');
        if ($submits) {
            //接受参数
            $account = $this->input->post('account');
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $username = $this->input->post('userName');
            $position = $this->input->post('position');
            $role = $this->input->post('role');
            $roleNameId = explode('_' , $role);
            $roleId = $roleNameId[0];
            $roleName = $roleNameId[1];
            $curlang = $this->config->item('language');
            //验证是否存在
            $sql = "select * from $this->t_user where account = '$account' or  email = '$email' ";
            $userFirst = $this->common_model->getQuery($sql , 'row_array');
            if ($userFirst) {
                $message = '帐号或邮箱已被注册';
            }
            else {
                $inary = array('account' => $account , 'password' => md5($password) , 'name' => $username , 'email' => $email , 'position' => $position , 'role' => $roleName , 'role_id' => $roleId , 'addtime' => time() , 'erp_language' => $curlang);
                $result_id = $this->common_model->insert($this->t_user , $inary);
                $message = '注册成功';
            }
            js_goto(blang_url('home/login/?account=' . $account . '&password=' . $password . '&submits=yes') , $message);
        }
        else {
            //角色类型
            $roleList = $this->users_model->GetRole(1);
            $language = $this->uri->segment(1);
            foreach ($roleList as &$row) {
                switch ($language) {
                    case 'sc':
                        $row['name'] = $row['name_ch'];
                        break;
                    case 'english':
                        $row['name'] = $row['name_en'];
                        break;
                    default:
                        $row['name'] = $row['name_en'];
                        break;
                }
            }
            unset($row);
            $data['roleList'] = $roleList;
            //视图以及样式
            //$this->load->view('defaults/common/header');
            $this->load->view('defaults/register' , $data);
            $this->load->view('defaults/common/footer');
        }
    }

    /**
     * 判断帐号是否可用
     */
    function valid_account()
    {
        $account = $this->input->get('account');
        $userData = $this->common_model->selectFirst($this->t_user , array('account' => $account));
        echo $userData ? 1 : 0;
        exit;
    }

    /**
     * 验证密码是否正确
     */
    function valid_pwd()
    {
        $account = $this->input->get('account');
        $password = $this->input->get('password');
        $userFirst = $this->common_model->selectFirst($this->t_user , array('account' => $account , 'password' => md5($password)));
        echo $userFirst ? 1 : 0;
        exit;
    }

    /**
     * 找回密码
     */
    function forgetPwd()
    {
        //接收参数
        $email = $this->input->post('email');
        if (empty($email) || !filter_var($email , FILTER_VALIDATE_EMAIL)) {
            $message = '您输入的邮箱不正确';
        }
        else {
            //判断邮箱用户是否存在
            $result = $this->common_model->selectFirst($this->t_member , array('email' => $email));
            if (empty($result)) {
                $message = '你输入的用户邮箱不存在';
            }
            else {
                //生成随机八位数密码
                $randPwd = substr(md5(time()) , 0 , 8);
                $result_send = $this->common_model->sendEmail(array('assign' => 'email_forgetpwd' , 'emails' => $email , 'code' => $randPwd));
                if ($result_send) {
                    $this->common_model->update($this->t_member , array('password' => md5($randPwd)) , array('email' => $email));
                    $message = '发送成功';
                }
                else {
                    $message = '发送失败';
                }
            }
            js_goto('' , $message , true);
        }
    }

    /**
     * 登陆的相关统计
     */
    function _addUserLog()
    {
        $users = $this->session->userdata('users');
        $userData = $this->common_model->selectFirst($this->t_user , array('id' => $users['id']));
        $inary = array('account' => $users['account'] , 'login_ip' => $users['curip']);
        if (empty($userData)) {
            $this->common_model->insert($this->t_loguser , $inary);
        }
        else {
            $where = array('id' => $users['id']);
            $inary['login_time'] = date('Y-m-d H:i:s');
            $this->common_model->update($this->t_loguser , $inary , $where);
        }
    }

    /**
     * 退出
     */
    function userQuit()
    {
        $this->session->sess_destroy();
        redirect(blang_url());
    }

    /**
     * 权限树
     * @param $role_id
     * @return mixed
     */
    private function PermissionTree($role_id)
    {
        if (is_string($role_id)) {
            $role_id = explode(',', $role_id);
        }
        //如果是超级管理员
        if (in_array(1, $role_id)) {
            $tree = $this->users_model->getRolePermissionTree(null);
        }else{
            $tree = $this->users_model->getRolePermissionTree($role_id);
        }
        return $tree;
    }

    function index()
    {


        $this->users = $this->session->userdata('users');
        if (empty($this->users)) {
            redirect(blang_url('/'));
        }
        //print_r($this->users);die;
        //超级管理员开启调试模式
        //***********************
        $my_lang = $this->uri->segment(1);
        $optlang[$my_lang] = 'selected';
        $data['optlang'] = $optlang;
        $data['users'] = $this->users;
        define('MYLANG' , $my_lang);

        $this->load->model('users_model');
        $data['rolename'] = $this->users_model->getRolesByIds(rtrim($this->users['role_id'] , ','));

        $get_debug = $this->input->get('debug');
        if ($get_debug) {
            $this->session->set_userdata('user_debug' , $get_debug);
        }
        $user_debug = $this->session->userdata('user_debug');
        define('MYDEBUG' , $user_debug);
        $this->lang->load('home'); //加载语言包
        if ($user_debug == 'true') {
            $this->output->enable_profiler(TRUE); //分析器
        }
        $users = $this->users;
        $data['users'] = $users;
        if (empty($users['franchisees_id'])) {
            $sql = "select COUNT(id) as cnt,status_id from mt_order  GROUP BY status_id";
        }
        else {
            $sql = sprintf("select COUNT(id) as cnt,status_id from mt_order where mt_order.napa_stores_num ='%s' GROUP BY status_id" , $users['franchisees_id']);
        }
        $cnts = $this->common_model->getQuery($sql , 'result_array');
        $kk = 'ch';

        switch (MYLANG) {
            case 'sc':
                $kk = 'ch';
                break;
            case 'english':
                $kk = 'en';
                break;
            case 'es':
                $kk = 'es';
                break;
        }

        foreach ($cnts as $k => $v) {

            $status = $this->common_model->selectFirst('mt_order_status' , array('id' => $v['status_id']));

            $key = 'name_' . $kk;
            $cnts[$k]['status'] = $status[$key];
        }

        $data['cnts'] = $cnts;
        //权限树
        $this->permissionTree = $this->PermissionTree($this->users['role_id']);

        //$this->load->model('fee_model');
        //echo 'xx:'.$this->fee_model->setShippingPrice('10020');
       
       
       //$this->pushMultiSF('1008');

        $this->load->view('defaults/common/header' , $data);
        $this->load->view('defaults/index');
    }
    
    function testShipping()
    {
    	$this->load->model('fee_model');
	$gp= gp();
        echo 'xx:'.$this->fee_model->setShippingPrice(trim($gp['pid']));
    }

     /**
     * 推送订单到SF
     * @param string $id
     */
    function pushMultiSF($id = '')
    {
        $this->load->model('salesforce_model' , 'sfModel');
        $result = $this->sfModel->oms_to_sf001_multiorder($id);
	print_r($result);
        if ($result['status']) {
            $this->common_model->update('mt_multi_orders' , array('isSync_sf' => 1) , array('id' => $id));
        }
        if (is_array($result)) {
            gsh_output($result);
        }
        else {
            echo $result;
        }
    }
    
    
    /**
     * 推送订单到SF
     * @param string $id
     */
    function pushSF($id = '')
    {
        $this->load->model('salesforce_model' , 'sfModel');
        $result = $this->sfModel->oms_to_sf001($id);
	print_r($result);
        if ($result['status']) {
            $this->common_model->update('mt_order' , array('isSync_sf' => 1) , array('id' => $id));
        }
        if (is_array($result)) {
            gsh_output($result);
        }
        else {
            echo $result;
        }
    }

    public function ajaxGet4pxCode()
    {

        $url = "http://open.sandbox.4px.com/authorize/get?client_id=0ec112f2-1c23-4399-9150-e9a3fc1c8882&response_type=code";
        //3.拉取用户的opendi
        header('location:' . $url);

    }


    public function createSign($key , $tmp , $method , $secret , $body)
    {

        $str = 'app_key' . ($key) . 'formatjsonmethod' . ($method) . 'timestamp' . ($tmp) . 'v1.0' . ($body) . ($secret);

        // echo(($str) . "\n");
        return (md5($str));
    }

    public function Get4ptApiValue()
    {
        $api4px = $this->db->query("select * from `mt_4px_api`")->result_array();
        $arr_return = array();
        foreach ($api4px as $k => $v) {
            $arr_return[$v['key']] = $v;
        }
        return $arr_return;
    }

    /**
     * 创建Token
     */
    public function createToken()
    {

        $api_arr = $this->Get4ptApiValue();
        $url = 'http://open.sandbox.4px.com/accessToken/get';
        $post_data['client_id'] = $api_arr['app_key']['value'];//
        $post_data['client_secret'] = $api_arr['app_secret']['value'];//
        $post_data['grant_type'] = 'authorization_code';
        $post_data['code'] = $api_arr['authorization_code']['value'];//
        $post_data['redirect_uri'] = 'http://sandbox.tomrepair.es';
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . ($v) . "&";
        }
        $post_data = substr($o , 0 , -1);
        $res = $this->vpost($url , $post_data);
        $res = json_decode($res);
        $this->db->query(sprintf("update `mt_4px_api` set `value`='%s',`add_time` = '%s' WHERE  `key` = 'refresh_token' " , $res->refresh_token , time()));
        $this->db->query(sprintf("update `mt_4px_api` set `value`='%s',`add_time` = '%s' WHERE  `key` = 'access_token' " , $res->access_token , time()));

    }

    public function getChannel()
    {

        $api_arr = $this->Get4ptApiValue();
        $key = $api_arr['app_key']['value'];//APP唯一ID,
        $secret = $api_arr['app_secret']['value'];//APP密钥
        $tmp = date("Y-m-d H:i:s" , time());

        $method = 'fb4.wms.country.list';
        $acctoken = $api_arr['access_token']['value'];
        $sign = $this->createSign($key , $tmp , $method , $secret,"");
		//echo("{".$sign."}");
		$str_tt = 'app_key' . ($key) . 'formatjsonmethod' . ($method) . 'timestamp' . ($tmp) . 'v1.0'  . ($secret);
		//echo("_____".$str_tt."______");
        $url = "http://open.sandbox.4px.com/router/api/service";

        $post_data['method'] = $method;
        $post_data['v'] = '1.0';
        $post_data['app_key'] = $key;

        $post_data['timestamp'] = urlencode($tmp);
        $post_data['format'] = 'json';
        $post_data['access_token'] = $acctoken;
        $post_data['sign'] = $sign;

        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . ($v) . "&";
        }

        $post_data = substr($o , 0 , -1);
        $header = array('Content-Type: applocation/json;charset=UTF-8');
		//print_r($url . '?' . $post_data );
        $res = $this->vpost($url . '?' . $post_data , null , $header);
		echo($url . '?' . $post_data."\n");
        print_r($res);

    }

    public function doMethod()
    {

        $api_arr = $this->Get4ptApiValue();
        $key = $api_arr['app_key']['value'];//APP唯一ID,
        $secret = $api_arr['app_secret']['value'];//APP密钥
        $tmp = date("Y-m-d H:i:s" , time());

        $method = 'fb4.wms.deliveryOrder.create';
        $acctoken = $api_arr['access_token']['value'];
      
        $body ='{"warehouseCode":"USLA","channelCode":"LAUPS","referenceCode":"wx1000008611111","phone":"15877777777","postalCode":"95673","street":"ELKHORN BLVD","city":"RIO LINDA","state":"CA","countryCode":"US","name":"Theo dhht","lstSku":[{"sku":"TOMREPAIRAPI001","quantity":"1"}]}';

	
        $sign = $this->createSign($key , $tmp , $method , $secret , $body);
        $url = "http://open.sandbox.4px.com/router/api/service";


        $post_data['method'] = $method;
        $post_data['v'] = '1.0';
        $post_data['app_key'] = $key;

        $post_data['timestamp'] =urlencode ($tmp);
        $post_data['format'] = 'json';
        $post_data['access_token'] = $acctoken;
  	//$post_data['body'] = $body;
        $post_data['sign'] = $sign;
      
        //print_r($post_data);

        $o = "";
        foreach ($post_data as $k => $v) {
		
 					$o .= "$k=" . ($v) . "&";
			
        }

        $post_data = substr($o , 0 , -1);
        $header = array('Content-Type: applocation/json;charset=UTF-8' , 'Content-Length:' . strlen($body));

		echo($url . '?' . $post_data);
        $res = $this->vpost($url . '?' . $post_data ,$body , $header);
       
        print_r($res);
    }

    function vpost($url , $data , $headers = array())
    {
        $curl = curl_init(); // 启动一个CURL会话
        if ($headers && is_array($headers)) {
            curl_setopt($curl , CURLOPT_HTTPHEADER , $headers);
        }
        curl_setopt($curl , CURLOPT_URL , $url); // 要访问的地址
        curl_setopt($curl , CURLOPT_SSL_VERIFYPEER , 0); // 对认证证书来源的检查
        curl_setopt($curl , CURLOPT_SSL_VERIFYHOST , 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl , CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器

        curl_setopt($curl , CURLOPT_FOLLOWLOCATION , 1); // 使用自动跳转
        curl_setopt($curl , CURLOPT_AUTOREFERER , 1); // 自动设置Referer
        curl_setopt($curl , CURLOPT_POST , 1); // 发送一个常规的Post请求
        curl_setopt($curl , CURLOPT_POSTFIELDS , $data); // Post提交的数据包
        curl_setopt($curl , CURLOPT_TIMEOUT , 30); // 设置超时限制防止死循环
        curl_setopt($curl , CURLOPT_HEADER , 0); // 显示返回的Header区域内容
        curl_setopt($curl , CURLOPT_RETURNTRANSFER , 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $tmpInfo; // 返回数据
    }


        function php1()
        {
            print_r(ini_get_all());

        }
	
	
	function doPustMulti()
	{
	$gp = gp();
	$this->pushMultiSF($gp['id']);
	//$this->pushSF($gp['id']);
	}

}
